export default {
  name: 'e-minder-hotbox',
  props: {
    minder: {
      type: Object
    },
    menus: {
      type: Array
    },
    // 是否可编辑
    editable: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      hotbox: null,
      downX: 0,
      downY: 0
    }
  },
  watch: {
    // minder 渲染完成后触发hotbox初始化 只会触发一次
    minder: function() {
      this.init()
    }
  },
  mounted() {
    document.body.append(this.$refs.hotbox)
  },
  methods: {
    // 初始化菜单
    init() {
      // eslint-disable-next-line no-undef
      this.hotbox = new HotBox(this.$refs.hotbox)

      const main = this.hotbox.state('main')
      this.menus.forEach(item => {
        main.button({
          position: item.position || 'ring',
          label: item.label,
          enable: () => {
            return (this.editable || item.position === 'center') && this.minder.getSelectedNode() ? item.enable(this.minder.getSelectedNode()) : false
          },
          key: item.key,
          action: () => {
            return item.action(this.minder.getSelectedNode())
          }
        })
      })

      const minderContainer = this.$parent.$refs.minder

      // 鼠标按下事件
      minderContainer.addEventListener('mousedown', (e) => {
        this.hotbox.active('idle')
        // 右键
        if (e.button === 2) {
          // 记录xy轴
          this.downX = e.clientX
          this.downY = e.clientY
        }
        e.preventDefault()
      }, false)

      // 鼠标按键松开
      minderContainer.addEventListener('mouseup', (e) => {
        if (e.button !== 2 || e.clientX !== this.downX || e.clientY !== this.downY) return

        const node = this.minder.getSelectedNode()
        if (!node) return

        // const box = node.getRenderBox()
        // this.hotbox.active('main', { x: box.cx, y: box.cy})
        // 由于将hotbox追加到body 所以弹出位置使用鼠标点击的位置
        this.hotbox.active('main', { x: this.downX, y: this.downY })
      }, false)

      // 滚轮事件
      minderContainer.addEventListener('mousewheel', () => {
        this.hotbox.active('idle')
      }, false)

      // 阻止热盒事件冒泡，在热盒正确执行前导致热盒关闭
      this.$refs.hotbox.addEventListener('mousedown', function(e) {
        e.stopPropagation()
      })

      // 屏蔽原生右键
      this.$refs.hotbox.addEventListener('contextmenu', function(e) {
        e.preventDefault()
      })
    },
    // 触发事件
    dispatch(event) {
      this.hotbox.dispatch(event)
    }
  },
  beforeDestroy() {
    this.$refs.hotbox.remove()
  },
  deactivated() {
    if (this.hotbox) {
      this.hotbox.active('idle')
    }
  },
  destroyed() {
    this.$el.remove()
  },
  render(h) {
    return h('div', {
      ref: 'hotbox'
    })
  }
}
